import scrapy
import requests,json
from bid.items import BidItem
from bid.tools import *


class HenanSpider(scrapy.Spider):
    name = 'henan'
    allowed_domains = ['hnsggzyfwpt.hndrc.gov.cn/']
    start_urls = ['http://hnsggzyfwpt.hndrc.gov.cn/']
    url = 'http://hnsggzyfwpt.hndrc.gov.cn/services/hl/getSelect?response=application/json&pageIndex=%s&pageSize=22&day=&sheng=x1&qu=&xian=&title=&timestart=&timeend=&categorynum=002&siteguid=9f5b36de-4e8f-4fd6-b3a1-a8e08b38ea38'
    t_dic ={
        '002001001':['工程建设-招标公告','1'],
        '002001002':['工程建设-变更公告','2'],
        '002001003':['工程建设-评标结果公示','2'],
        '002001004':['工程建设-中标结果公示','3'],
        '002002001':['政府采购-采购公告','1'],
        '002002002':['政府采购-变更公告','2'],
        '002002003':['政府采购-结果公示','3'],
        '002006001':['其他公告-交易公告','1'],
        '002006002':['其他公告-成交公告','3'],
    }
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36'}
    msg =[]
    def start_requests(self):
        for page in range(1,99999999):
            res = requests.get(url=self.url%page,headers=self.headers).json()
            ls = json.loads(res['return'])['Table']
            if not ls:
                break
            for l in ls:
                item = {}
                item['link'] = 'http://hnsggzyfwpt.hndrc.gov.cn' + l['href']
                key = item['link'].split('/')[-3]
                if key not in self.t_dic:
                    continue
                item['title'] = l['title']
                item['time'] = l['infodate']
                item['classification'] = '河南-'+self.t_dic[key][0]
                item['typ']=self.t_dic[key][-1]
                if redis_dupefilter(item) or item['time'].startswith('2021'):
                    self.msg.append(page)
                    break
                yield scrapy.Request(url=item['link'], callback=self.parse, meta={'item': item})
            if page in self.msg:
                print('完成')
                break
            time.sleep(len(ls))

    def parse(self, response):
        item = BidItem()
        item.update(response.meta['item'])
        item['content'] = get_content(response.text, '//div[@class="ewb-left-bd"]')
        item = get_field(dict(item))
        yield item